﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Windows;
using System.Xml.Serialization;

namespace churchtool.Data
{
    public class GlobalSettings
    {
        private static GlobalSettings singelton;

        private GlobalSettings()
        {
            Language = Thread.CurrentThread.CurrentCulture.ToString();
        }

        [XmlElement(DataType = "string", ElementName = "DefaultFilePath")]
        public string DefaultFilePath;

        [XmlElement(DataType = "string", ElementName = "Language")]
        public string Language;

        public static GlobalSettings GetInstance()
        {
            if (singelton == null)
            {
                DeserializeFromXML();
                if (singelton == null)
                    singelton = new GlobalSettings();
            }

            return singelton;
        }

        public static void SerializeToXML()
        {
            // Create the XmlSerializer.
            XmlSerializer s = new XmlSerializer(typeof(GlobalSettings));

            // To write the file, a TextWriter is required.
            string foldername = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Churchtool";
            string filename = "SermonUpload_Settings.xml";

            if (!File.Exists(Path.Combine(foldername, filename)))
            {
                Directory.CreateDirectory(foldername);
                var fileStream =  File.Create(Path.Combine(foldername, filename));
                fileStream.Close();
            }

            TextWriter writer = new StreamWriter(Path.Combine(foldername, filename));

            // Serialize the object, and close the TextWriter.      
            s.Serialize(writer, singelton);
            writer.Close();
        }

        public static void DeserializeFromXML()
        {
            try
            {
                FileStream fs = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Churchtool\\SermonUpload_Settings.xml", FileMode.Open);
                XmlSerializer x = new XmlSerializer(typeof(GlobalSettings));
                singelton = (GlobalSettings)x.Deserialize(fs);
            }
            catch { }
        }
    }
}

